#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <memory>
#include <typeinfo>
#include <cstring>
#include <cstdint>
#include <cassert>
#include <ctime>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <pthread.h>
#include <signal.h>


#define INF 1
#define DBG 2
#define ERR 3
#define LOG_LEVEL ERR
#define LOG(level, format, ...) do{\
    if (level < LOG_LEVEL) break; \
    time_t t = time(nullptr);\
    struct tm* ltm = localtime(&t);\
    char tmp[64] = {0};\
    sprintf(tmp, "%04d-%02d-%02d %02d:%02d:%02d", ltm->tm_year + 1900, \
        ltm->tm_mon + 1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);\
    fprintf(stdout, "[%p %s %s:%d] " format "\n", (void*)pthread_self(), tmp, __FILE__, __LINE__, ##__VA_ARGS__); \
}while(0)

#define INF_LOG(format, ...) LOG(INF, format, ##__VA_ARGS__)
#define DBG_LOG(format, ...) LOG(DBG, format, ##__VA_ARGS__)
#define ERR_LOG(format, ...) LOG(ERR, format, ##__VA_ARGS__)


#define BUFFER_DEFAULT_SIZE 1024
class Buffer
{
private:
    std::vector<char> _buffer;  // 使用vector进行内存空间管理
    uint64_t _read_idx;         // 读偏移量
    uint64_t _write_idx;        // 写偏移量
public:
    Buffer() :_buffer(BUFFER_DEFAULT_SIZE), _read_idx(0), _write_idx(0) {}
    char* Begin() { return &*_buffer.begin(); }
    // 获取当前写入起始地址
    char* WritePosition() { return Begin() + _write_idx; }
    // 获取当前读取起始地址
    char* ReadPosition() { return Begin() + _read_idx; }
    // 获取缓冲区末尾剩余空间大小--写偏移之后的空间
    uint64_t TailIdleSize() { return _buffer.size() - _write_idx; }
    // 获取缓冲区头部剩余空间大小--读偏移之前的空间
    uint64_t HeadIdleSize() { return _read_idx; }
    // 获取可读数据大小
    uint64_t ReadableSize() { return _write_idx - _read_idx; }
    // 将读偏移向后移动
    void MoveReadOffset(uint64_t len) 
    {
        assert(len <= ReadableSize());
        _read_idx += len;   
    }
    // 将写偏移向后移动
    void MoveWriteOffset(uint64_t len)
    {
        assert(len <= TailIdleSize());
        _write_idx += len;
    }
    // 确保空间可以写入(如果空间足够就移动数据，否则进行扩容)
    void EnsureWriteSpace(uint64_t len)
    {
        if (TailIdleSize() >= len) return;
        if (HeadIdleSize() + TailIdleSize() >= len)
        {
            uint64_t rsz = ReadableSize();
            std::copy(ReadPosition(), ReadPosition() + rsz, Begin());
            _read_idx = 0;
            _write_idx = rsz;
        }
        else
        {
            _buffer.resize(_write_idx + len);
        }
    }
    // 写入数据
    void Write(const void* data, uint64_t len)
    {
        EnsureWriteSpace(len);
        const char* d = (const char*)data;
        std::copy(d, d + len, WritePosition());
    }
    void WriteAndPush(const void* data, uint64_t len)
    {
        if (len == 0) return;
        Write(data, len);
        MoveWriteOffset(len);
    }
    void WriteString(const std::string& str)
    {
        Write(str.c_str(), str.size());
    }
    void WriteStringAndPush(const std::string& str)
    {
        WriteString(str);
        MoveWriteOffset(str.size());
    }
    void WriteBuffer(Buffer& buffer)
    {
        Write(buffer.ReadPosition(), buffer.ReadableSize());
    }
    void WriteBufferAndPush(Buffer& buffer)
    {
        WriteBuffer(buffer);
        MoveWriteOffset(buffer.ReadableSize());
    }
    // 读取数据
    void Read(void* buf, uint64_t len)
    {
        assert(len <= ReadableSize());
        std::copy(ReadPosition(), ReadPosition() + len, (char*)buf);
    }
    void ReadAndPop(void* buf, uint64_t len)
    {
        Read(buf, len);
        MoveReadOffset(len);
    }
    std::string ReadAsString(uint64_t len)
    {
        assert(len <= ReadableSize());
        std::string res;
        res.resize(len);
        Read(&res[0], len);
        return res;
    }
    std::string ReadAsStringAndPop(uint64_t len)
    {
        assert(len <= ReadableSize());
        std::string res = ReadAsString(len);
        MoveReadOffset(len);
        return res;
    }
    // 找到\r\n
    char* FindCRLF() 
    {
        char* res = (char*)memchr(ReadPosition(), '\n', ReadableSize());
        return res;
    }
    // 获取一行数据，通常是针对HTTP协议
    std::string GetLine()
    {
        char* pos = FindCRLF();
        if (pos == nullptr)
            return std::string();
        return ReadAsString(pos - ReadPosition() + 1);
    }
    std::string GetLineAndPop()
    {
        std::string res = GetLine();
        MoveReadOffset(res.size());
        return res;
    }
    // 清空数据
    void clear() { _read_idx = _write_idx = 0; }
};

#define MAX_LISTEN 1024
class Socket
{
private:
    int _sockfd;
public:
    Socket():_sockfd(-1) {};
    Socket(int sockfd) :_sockfd(sockfd) {};
    ~Socket(){ Close(); }
    int Fd() { return _sockfd; }
    // 创建套接字
    bool Create()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (_sockfd < 0)
        {
            ERR_LOG("CREATE SOCKET FAILED!");
            return false;
        }
        return true;
    }
    bool Bind(const std::string& ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = bind(_sockfd, (struct sockaddr*)&addr, len);
        if (ret < 0)
        {
            ERR_LOG("BIND ADDRESS FAILED!");
            return false;
        }
        return true;
    }
    bool Listen(int backlog = MAX_LISTEN)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0)
        {
            ERR_LOG("LISTEN SOCKET FAILED!");
            return false;
        }
        return true;
    }
    bool Connect(const std::string& ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(struct sockaddr_in); 
        int ret = connect(_sockfd, (struct sockaddr*)&addr, len);
        if (ret < 0)
        {
            ERR_LOG("CONNECT SERVER FAILED!");
            return false;
        }
        return true;
    }
    int Accept()
    {
        int newfd = accept(_sockfd, nullptr, nullptr);
        if (newfd < 0)
        {
            ERR_LOG("SOCKET ACCEPT FAILED!");
            return -1;
        }
        return newfd;
    }
    void Close()
    {
        if (_sockfd != -1)
        {
            close(_sockfd);
            _sockfd = -1;
        }
    }
    // 接收数据
    ssize_t Recv(void* buf, size_t len, int flag = 0)
    {
        ssize_t ret = recv(_sockfd, buf, len, flag);
        if (ret <= 0)
        {
            if (errno == EAGAIN || errno == EINTR)
            {
                return 0;
            }
            ERR_LOG("SOCKET RECV FAILED!");
            return -1;
        }
        return ret;
    }
    ssize_t NonBlockRecv(void* buf, size_t len)
    {
        return Recv(buf, len, MSG_DONTWAIT);  // MSG_DONTWAIT 表示当前接收为非阻塞
    }
    // 发送数据
    ssize_t Send(const void* buf, size_t len, int flag = 0)
    {
        ssize_t ret = send(_sockfd, buf, len, flag);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                return 0;
            }
            ERR_LOG("SOCKET SEND FAILED!");
            return -1;
        }
        return ret;
    }
    ssize_t NonBlockSend(void* buf, size_t len)
    {
        if (len == 0) return 0;
        return Send(buf, len, MSG_DONTWAIT);  // MSG_DONTWAIT 表示当前发送为非阻塞
    }
    // 创建一个服务端连接
    bool CreateServer(uint16_t port, const std::string& ip = "0.0.0.0", bool block_flag = false)
    {
        // 1.创建套接字 2.设置为非阻塞 3.绑定 4.监听 5.设置地址复用
        if (Create() == false) return false;
        if (block_flag) NonBlock();
        ReuseAddress();
        if (Bind(ip, port) == false) return false;
        if (Listen() == false) return false;
        return true;
    }
    // 创建一个客户端连接
    bool CreateClient(uint16_t port, const std::string& ip)
    {
        if (Create() == false) return false;
        if (Connect(ip, port) == false) return false;
        return true;
    }
    // 设置套接字选项——设置地址复用
    void ReuseAddress()
    {
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
    // 设置套接字阻塞属性——设置为非阻塞
    void NonBlock()
    {
        int fl = fcntl(_sockfd, F_GETFL);
        fcntl(_sockfd, F_SETFL, fl | O_NONBLOCK);
    }
};

class EventLoop;
class Channel
{
private:
    int _fd;
    EventLoop* _loop;
    uint32_t _events;    // 监控哪些事件
    uint32_t _revents;   // 哪些事件就绪
    using EventCallBack = std::function<void()>;
    EventCallBack _read_callback;
    EventCallBack _write_callback;
    EventCallBack _error_callback;
    EventCallBack _close_callback;
    EventCallBack _event_callback;
public:
    Channel(EventLoop* loop, int fd):_fd(fd), _events(0), _revents(0), _loop(loop) {};
    int Fd() { return _fd; }
    uint32_t Events() { return _events; }
    void SetRevents(uint32_t events) { _revents = events; }
    void SetReadCallBack(const EventCallBack& cb) { _read_callback = cb; }
    void SetWriteCallBack(const EventCallBack& cb) { _write_callback = cb; }
    void SetErrorCallBack(const EventCallBack& cb) { _error_callback = cb; }
    void SetCloseCallBack(const EventCallBack& cb) { _close_callback = cb; }
    void SetEventCallBack(const EventCallBack& cb) { _event_callback = cb; }
    // 当前是否监控了可读
    bool ReadAble() { return _events & EPOLLIN; }
    bool WriteAble() { return _events & EPOLLOUT; }
    void EnableRead() { _events |= EPOLLIN; Update(); }
    void EnableWrite() { _events |= EPOLLOUT; Update(); }
    void DisableRead() { _events &= ~EPOLLIN; Update(); }
    void DisableWrite(){_events &= ~EPOLLOUT; Update(); }
    void DisableAll(){_events = 0; Remove(); }
    // 移除监控
    void Remove();
    void Update();
    // 连接触发事件调用该函数
    void HandlerEvent()
    {
        if ((_revents & EPOLLIN) || (_revents & EPOLLRDHUP) || (_revents & EPOLLPRI))
        {
            if (_read_callback) _read_callback();
        }
        // 有可能会释放连接的操作事件，一次只处理一个
        if (_revents & EPOLLOUT)
        {
            if (_write_callback) _write_callback();
        }
        else if (_revents & EPOLLERR)
        {
            if (_error_callback) _error_callback();
        }
        else if (_revents & EPOLLHUP)
        {
            if (_close_callback) _close_callback();
        }
        // 任意事件回调函数
        if (_event_callback) _event_callback();
    }
};

#define MAX_EPOLLEVENTS 1024
class Poller
{
private:
    int _epfd;
    struct epoll_event _evs[MAX_EPOLLEVENTS];
    std::unordered_map<int, Channel*> _channels;
private:
    void Update(Channel* channel, int op)
    {
        struct epoll_event ev;
        ev.data.fd = channel->Fd();
        ev.events = channel->Events();
        int ret = epoll_ctl(_epfd, op, channel->Fd(), &ev);
        if (ret < 0)
        {
            ERR_LOG("EPOLLCTL FAILED!");
        }
    }
    bool HasChannel(Channel* channel)
    {
        auto it = _channels.find(channel->Fd());
        return it != _channels.end();
    }
public:
    Poller()
    {
        _epfd = epoll_create(MAX_EPOLLEVENTS);
        if (_epfd < 0)
        {
            ERR_LOG("EPOLL CREATE FAILED!");
            abort();
        }
    }
    // 更新：已经存在就更新否则添加
    void UpdateEvent(Channel* channel)
    {
        if (!HasChannel(channel))
        {
            _channels.insert(std::make_pair(channel->Fd(), channel));
            Update(channel, EPOLL_CTL_ADD); 
        }
        else
        {
            Update(channel, EPOLL_CTL_MOD);  
        }
    }
    // 移除监控
    void RemoveEvent(Channel* channel)
    {
        auto it = _channels.find(channel->Fd());
        if (it != _channels.end())
        {
            _channels.erase(it);
        }
        Update(channel, EPOLL_CTL_DEL);
    }
    // 开始监控，返回活跃的channel
    void Poll(std::vector<Channel*>* active)
    {
        int nfds = epoll_wait(_epfd, _evs, MAX_EPOLLEVENTS, -1);
        if (nfds < 0)
        {
            if (errno == EINTR)
                return;
            ERR_LOG("EPOLL WAIT FAILED!");
            abort();  // 退出程序
        }
        for (int i = 0; i < nfds; i++)
        {
            auto it = _channels.find(_evs[i].data.fd);
            assert(it != _channels.end());
            it->second->SetRevents(_evs[i].events);
            active->push_back(it->second);
        }
    }
};


using TaskFunc = std::function<void()>;
using ReleaseFunc = std::function<void()>;
class TimerTask{
    private:
        uint64_t _id;           // 定时器任务对象ID
        uint32_t _timeout;      // 定时器任务超时时间
        TaskFunc _task_cb;      // 定时器对象要执行的定时任务
        bool _canceled;         // 定时任务是否被取消 
        ReleaseFunc _release;   // 用于删除TimeWheel中保存的定时器对象信息
    public:
        TimerTask(uint64_t id, uint32_t delay, const TaskFunc& cb)
        :_id(id), _timeout(delay), _task_cb(cb), _canceled(false)
        {}
        ~TimerTask() 
        { 
            if (_canceled == false)
            {
                _task_cb(); 
            }
            _release(); 
        }
        void Cancel() { _canceled = true; }
        void SetRelease(const ReleaseFunc& cb) { _release = cb; }
        uint32_t DelayTime() { return _timeout; }
};

class TimerWheel{
    private:
        using PtrTask = std::shared_ptr<TimerTask>;
        using WeakTask = std::weak_ptr<TimerTask>;
        int _tick;                                      // 秒针-走到哪哪里的任务就要被执行
        int _capacity;                                  // 表盘最大数量-也就是最大延迟时间
        std::vector<std::vector<PtrTask>> _wheel;       // 时间轮
        std::unordered_map<uint64_t, WeakTask> _timers; // 使用弱引用，方便刷新/延迟定时任务
        
        EventLoop* _loop;                               
        int _timer_fd;                                  // 用来做事件通知，让指针每秒往后走执行定时任务
        std::unique_ptr<Channel> _timer_channel;        // 对_timer_fd事件管理
    private:
        void RemoveTimer(uint64_t id)
        {
            auto it = _timers.find(id);
            if (it != _timers.end())
            {
                _timers.erase(it);
            }
        }
        static int CreateTimerFd()
        {
            int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
            if (timerfd < 0)
            {
                ERR_LOG("CREATE TIMERFD FAILED!");
                abort();
            }
            struct itimerspec itime;
            itime.it_value = {1, 0};
            itime.it_interval = {1, 0};
            timerfd_settime(timerfd, 0, &itime, nullptr);
            return timerfd;
        }
        // 有可能因为其他文件描述符的事件处理花费事件比较长，等待处理定时器描述符事件的时候，已经超时很多次了
        // 而读取的数据是超时的次数，但是在OnTime只进行了一次处理，因此需要返回次数进行多次处理
        uint64_t ReadTimerFd()
        {
            uint64_t times;
            int ret = read(_timer_fd, &times, sizeof(times));
            if (ret < 0)
            {
                if (errno == EINTR || errno == EWOULDBLOCK)
                    return 0;
                ERR_LOG("READ TIMERFD FAILED!");
                abort();
            }
            return times;
        }
        // 这个函数应该每秒钟被执行一次，相当于秒针向后走一步
        void RunTimerTask()
        {
            _tick = (_tick + 1) % _capacity;
            _wheel[_tick].clear(); // 清空该位置数组，就会把数组中所有的定时器对象的shared_ptr释放掉
        }
        void OnTime()
        {
             //根据实际超时的次数，执行对应的超时任务
            uint64_t times = ReadTimerFd();
            for (int i = 0; i < times; i++) {
                RunTimerTask();
            }
        }
        // 添加定时任务
        void TimerAddInLoop(uint64_t id, uint32_t delay, const TaskFunc& cb)
        {
            PtrTask pt(new TimerTask(id, delay, cb));
            pt->SetRelease(std::bind(&TimerWheel::RemoveTimer, this, id));
            int pos = (_tick + delay) % _capacity;
            _wheel[pos].push_back(pt);
            _timers[id] = WeakTask(pt);
        }
        // 刷新/延迟定时任务
        void TimerRefreshInLoop(uint64_t id)
        {
            auto it = _timers.find(id);
            if (it == _timers.end())
            {
                return;
            }
            PtrTask pt = it->second.lock();
            int pos = (_tick + pt->DelayTime()) % _capacity;
            _wheel[pos].push_back(pt);
        } 
        // 取消定时任务
        void TimerCancelInLoop(uint64_t id)
        {
            auto it = _timers.find(id);
            if (it == _timers.end())
                return;
            PtrTask pt = it->second.lock();
            if (pt) pt->Cancel();
        }
    public:
        TimerWheel(EventLoop* loop):_tick(0), _capacity(60), _wheel(_capacity)
        , _loop(loop), _timer_fd(CreateTimerFd()), _timer_channel(new Channel(loop, _timer_fd))
        {
            _timer_channel->SetReadCallBack(std::bind(&TimerWheel::OnTime, this));
            _timer_channel->EnableRead(); 
        }   
        // 可能有多个外部线程进行定时器任务的添加/刷新，这样对_timers有线程安全
        // 所以我们要保证定时任务的操作必须在所对应的EventLoop线程中
        void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc& cb);
        void TimerRefresh(uint64_t id);
        void TimerCancel(uint64_t id);
        // 这个接口存在线程安全问题，只能在模块内，对应的EventLoop线程中运行
        bool HasTimer(uint64_t id)
        {
            auto it = _timers.find(id);
            return it != _timers.end();
        }
};

class Any
{
private:
    class holder
    {
    public:
        virtual ~holder() {}
        virtual const std::type_info& type() = 0;
        virtual holder* clone() = 0;
    };

    template<class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T& val) :_val(val){}
        virtual const std::type_info& type() { return typeid(_val); }
        virtual holder* clone() { return new placeholder(_val); }
        T _val;
    };

    holder* _content;
public:
    Any() :_content(nullptr){}
    Any(const Any& other) :_content(other._content ? other._content->clone() : nullptr) {}
    template<class T>
    Any(const T& val) :_content(new placeholder<T>(val)) {}
    ~Any() { delete _content; }

    template<class T>
    T* get() 
    {
        assert(typeid(T) == _content->type());
        return &((placeholder<T>*)_content)->_val;
    }

    Any& swap(Any& other)
    {
        std::swap(_content, other._content);
        return *this;
    }

    template<class T>
    Any& operator=(const T& val)
    {
        Any(val).swap(*this);
        return *this;
    }

    Any& operator=(const Any& other)
    {
        Any(other).swap(*this);
        return *this;
    }
};

class EventLoop
{
private:
    using Functor = std::function<void()>;
    std::thread::id _thread_id;                 // 线程ID
    int _event_fd;                              // 唤醒由于IO监控的阻塞，执行任务队列中的任务
    std::unique_ptr<Channel> _event_channel;    // eventfd对应的channel对象    
    Poller _poller;                             // 进行所有fd事件监控
    std::vector<Functor> _tasks;                // 任务池
    std::mutex _mutex;                          // 保护任务池
    TimerWheel _timer_wheel;                    // 定时任务模块
private:
    void RunAllTask()
    {
        std::vector<Functor> functor;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.swap(functor);
        }
        for (auto& f : functor)
        {
            f();
        }
    }
    static int CreateEventFd()
    {   
        int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
        if (efd < 0)
        {
            ERR_LOG("CREATE EVENTFD FAILED!");
            abort();
        }
        return efd;
    }
    void ReadEventFd()
    {
        uint64_t res;
        int ret = read(_event_fd, &res, sizeof(res));
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
            {
                return;
            }
            ERR_LOG("READ EVENTFD FAILED!");
            abort();
        }
    }
    void WakeUpEventFd()
    {
        uint64_t val = 1;
        int ret = write(_event_fd, &val, sizeof(val));
        if (ret < 0)
        {
            if (errno == EINTR)
                return;
            ERR_LOG("WRITE EVENTFD FAILED!");
            abort();
        }
    }
public: 
    EventLoop()
    :_thread_id(std::this_thread::get_id())
    ,_event_fd(CreateEventFd())
    ,_event_channel(new Channel(this, _event_fd))
    ,_timer_wheel(this)
    {
        _event_channel->SetReadCallBack(std::bind(&EventLoop::ReadEventFd, this));
        _event_channel->EnableRead();
    }
    // 执行：事件监控->就绪事件处理->执行任务
    void Start()
    {
        while (true)
        {
            std::vector<Channel*> actives;
            _poller.Poll(&actives);
            for (auto& e : actives)
            {
                e->HandlerEvent();
            }
            RunAllTask();
        } 
    }
    // 判断当前线程是否是EventLoop所对应的线程
    bool IsInLoop() { return _thread_id == std::this_thread::get_id(); }
    // 确保切换协议必须立即被执行，防止后续事件就绪触发但是使用的是之前的协议
    bool AssertInLoop() { return _thread_id == std::this_thread::get_id(); }
    // 如果要执行的任务在当前线程中则执行，否则入队列
    void RunInLoop(const Functor& cb)
    {
        if (IsInLoop())
            cb();
        else
            QueueInLoop(cb);
    }
    // 将任务插入任务队列
    void QueueInLoop(const Functor& cb)
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.push_back(cb);
        }
        WakeUpEventFd();
    }
    // 更新：添加/修改事件监控
    void UpdateEvent(Channel* channel) { _poller.UpdateEvent(channel); }
    // 移除事件监控
    void RemoveEvent(Channel* channel) { _poller.RemoveEvent(channel); }
    // 定时任务操作
    void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc& cb) { _timer_wheel.TimerAdd(id, delay, cb); }
    void TimerRefresh(uint64_t id) { _timer_wheel.TimerRefresh(id); }
    void TimerCancel(uint64_t id) { _timer_wheel.TimerCancel(id); }
    bool HasTimer(uint64_t id) { return _timer_wheel.HasTimer(id); }
};

void Channel::Remove() { _loop->RemoveEvent(this); }
void Channel::Update() { _loop->UpdateEvent(this); }
void TimerWheel::TimerAdd(uint64_t id, uint32_t delay, const TaskFunc& cb)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerAddInLoop, this, id, delay, cb));
}
void TimerWheel::TimerRefresh(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerRefreshInLoop, this, id));
}
void TimerWheel::TimerCancel(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerCancelInLoop, this, id));
}

class Connection;
using PtrConnection = std::shared_ptr<Connection>;
// DISCONNECTED -- 连接关闭状态      CONNECTING -- 连接建立成功，待处理状态
// CONNECTED -- 连接建立完成，各种设置已完成    DISCONNECTING -- 连接待关闭状态
typedef enum { DISCONNECTED, CONNECTING, CONNECTED, DISCONNECTING }ConnStatus;
// 使用shared_from_this必须继承enable_shared_from_this<>
class Connection : public std::enable_shared_from_this<Connection>
{
private:
    uint64_t _conn_id;              // 连接的唯一ID，方便进行管理和查找
    // uint64_t _timer_id;          // 连接定时任务ID，直接复用_conn_id即可
    ConnStatus _status;             // 连接的状态
    bool _enable_inactive_release;  // 是否启用连接非活跃销毁释放
    EventLoop* _loop;               // 连接所关联的EventLoop
    int _sockfd;                    // 连接关联的文件描述符fd
    Socket _socket;                 // 套接字管理
    Channel _channel;               // 连接的事件管理
    Buffer _in_buffer;              // 输入缓冲区
    Buffer _out_buffer;             // 输出缓冲区
    Any _context;                   // 处理上下文

    using ConnectedCallBack = std::function<void(const PtrConnection&)>;
    using MessageCallBack = std::function<void(const PtrConnection&, Buffer*)>; 
    using ClosedCallBack = std::function<void(const PtrConnection&)>; 
    using AnyEventCallBack = std::function<void(const PtrConnection&)>; 
    // 这四个函数是给服务器来设置的，而服务器是给用户设置的
    ConnectedCallBack _connected_callback; 
    MessageCallBack _message_callback; 
    ClosedCallBack _closed_callback; 
    AnyEventCallBack _event_callback; 
    // 组件的使用者，也就是服务器，要对组件，也就是所有连接进行管理，连接关闭需要调用该函数处理
    ClosedCallBack _server_closed_callback; 
private:
    // 五个事件就绪处理函数
    // 可读事件触发后的回调函数，接收socket的数据到缓冲区中，调用业务处理函数_message_callback;
    void HandlerRead()
    {
        char buffer[65536];
        ssize_t ret = _socket.NonBlockRecv(buffer, sizeof(buffer) - 1);
        if (ret < 0)
        {
            return ShutDownInLoop();
        }
        _in_buffer.WriteAndPush(buffer, ret);
        if (_in_buffer.ReadableSize() > 0)
        {
            _message_callback(shared_from_this(), &_in_buffer);
        }
    }
    // 可写事件触发后的回调函数，将发送缓冲区的数据进行发送
    void HandlerWrite()
    {
        ssize_t ret = _socket.NonBlockSend(_out_buffer.ReadPosition(), _out_buffer.ReadableSize());
        if (ret < 0)
        {
            if (_in_buffer.ReadableSize() > 0)
            {
                if (_message_callback) 
                    _message_callback(shared_from_this(), &_in_buffer);
            }
            return Release();
        }
        _out_buffer.MoveReadOffset(ret);
        if (_out_buffer.ReadableSize() == 0)
        {
            _channel.DisableWrite();
            if (_status == DISCONNECTING)
            {
                return Release();
            }
        }
    }
    // 触发挂断事件：此时套接字什么都做不了了，如果有数据就处理一下直接销毁即可
    void HandlerClose()
    {
        if (_in_buffer.ReadableSize() > 0)
        {
            if (_message_callback)
                _message_callback(shared_from_this(), &_in_buffer);
        }
        Release();
    }
    // 触发错误事件
    void HandlerError()
    {
        HandlerClose();
    }
    // 触发任意事件：1、刷新定时任务 2、调用组件使用者提供的回调函数
    void HandlerEvent()
    {
        if (_enable_inactive_release)
            _loop->TimerRefresh(_conn_id);
        if (_event_callback) 
            _event_callback(shared_from_this());
    }
    // 获取连接之后的操作：1、修改连接状态 2、启动可读监控 3、调用回调函数
    void EstablishedInLoop()
    {
        assert(_status == CONNECTING);
        // 启动可读监控必须在启动非活跃销毁释放之后。否则如果启动后读事件立马就绪，找不到对应的定时任务
        _status = CONNECTED;
        _channel.EnableRead();
        if (_connected_callback)
            _connected_callback(shared_from_this());
    }
    // 真正的释放连接操作：1、修改连接状态 2、移除连接的事件监控 3、关闭描述符 4、取消定时销毁任务 5、调用用户回调和服务回调函数
    // 问题是的里，在这个对象的成员函数中，应该在封装一层，然后把这个函数押入到任务队列中就解决了
    void Release(){
        _loop->QueueInLoop(std::bind(&Connection::ReleaseInLoop,this));
    }
    
    void ReleaseInLoop()
    {
        _status = DISCONNECTED;
        _channel.Remove();
        _socket.Close();
        if (_loop->HasTimer(_conn_id))
            _loop->TimerCancel(_conn_id);
        if (_closed_callback)
            _closed_callback(shared_from_this());
        if (_server_closed_callback)
            _server_closed_callback(shared_from_this());
    }
    // 并不是真正的发送接口，而是把数据放到发送缓冲区，启动可写事件监控
    void SendInLoop(Buffer& buf)
    {
        _out_buffer.WriteBufferAndPush(buf);
        if (_channel.WriteAble() == false)
        {
            _channel.EnableWrite();
        }
    }
    // 并非实际释放连接的操作，而是判断是否有数据待处理待发送
    void ShutDownInLoop()
    {
        _status = DISCONNECTING;
        if (_in_buffer.ReadableSize() > 0)
        {
            if (_message_callback) 
                _message_callback(shared_from_this(), &_in_buffer);
        }
        if (_out_buffer.ReadableSize() > 0)
        {
            if (_channel.WriteAble() == false)
                _channel.EnableWrite();
        }
        // 如果没有数据，或者接收缓冲区不足一个报文长度无法处理，直接释放
        if (_out_buffer.ReadableSize() == 0)
        {
            Release();
        }
    }
    // 启动非活跃连接释放：设置标志位，如果存在定时任务直接刷新，否则添加定时任务
    void EnableInactiveReleaseInLoop(int sec)
    {
        _enable_inactive_release = true;
        if (_loop->HasTimer(_conn_id))
            _loop->TimerRefresh(_conn_id);
        else
            _loop->TimerAdd(_conn_id, sec, std::bind(&Connection::Release, this));
    }
    void CancelInactiveReleaseInLoop()
    {
        _enable_inactive_release = false;
        if (_loop->HasTimer(_conn_id))
            _loop->TimerCancel(_conn_id); 
    }
    void UpgradeInLoop(const Any& context, const ConnectedCallBack& conn,
                 const MessageCallBack& msg, const ClosedCallBack& closed, 
                 const AnyEventCallBack& event)
    {
        _context = context;
        _connected_callback = conn;
        _message_callback = msg;
        _closed_callback = closed;
        _event_callback = event;
    }
public:
    Connection(EventLoop* loop, uint64_t conn_id, int sockfd)
    :_conn_id(conn_id), _status(CONNECTING), _enable_inactive_release(false)
    ,_loop(loop), _sockfd(sockfd), _socket(sockfd), _channel(_loop, _sockfd)
    {
        _channel.SetReadCallBack(std::bind(&Connection::HandlerRead, this));
        _channel.SetWriteCallBack(std::bind(&Connection::HandlerWrite, this));
        _channel.SetCloseCallBack(std::bind(&Connection::HandlerClose, this));
        _channel.SetErrorCallBack(std::bind(&Connection::HandlerError, this));
        _channel.SetEventCallBack(std::bind(&Connection::HandlerEvent, this));
    }
    ~Connection() { DBG_LOG("RELEASE CONNECTION:%p", this); }
    uint64_t Id() { return _conn_id; }
    int Fd() { return _sockfd; }
    // 判断连接是否处于CONNECTED状态
    bool Connected() { return _status == CONNECTED; }
    // 设置上下文，连接建立时调用
    void SetContext(const Any& context) { _context = context; }
    Any* GetContext() { return &_context; }
    void SetConnectedCallBack(const ConnectedCallBack& cb) { _connected_callback = cb; }
    void SetMessageCallBack(const MessageCallBack& cb) { _message_callback = cb; }
    void SetClosedCallBack(const ClosedCallBack& cb) { _closed_callback = cb; }
    void SetAnyEventCallBack(const AnyEventCallBack& cb) { _event_callback = cb; }
    void SetSvrClosedCallBack(const ClosedCallBack& cb) { _server_closed_callback = cb; }
    // 连接建立后，设置channel回调，并启动可写监控
    void Established() { _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop, this)); }
    // 将数据发送到输出缓冲区中，启动可写监控
    // 外界传入的是个临时空间，该操作可能是压入任务池还没有被执行，当被执行的时候，外界临时空间可能已经释放了
    void Send(const char* data, size_t len) 
    { 
        Buffer buf;
        buf.WriteAndPush(data, len);
        _loop->RunInLoop(std::bind(&Connection::SendInLoop, this, std::move(buf))); 
    }
    // 提供给组件的使用者关闭连接--需要完成剩余数据的处理
    void ShutDown() { _loop->RunInLoop(std::bind(&Connection::ShutDownInLoop, this)); }
    // 启动连接非活跃销毁释放
    void EnableInactiveRelease(int sec) { _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop, this, sec)); }
    // 取消连接非活跃销毁释放
    void CancelInactiveRelease() { _loop->RunInLoop(std::bind(&Connection::CancelInactiveReleaseInLoop, this)); }
    // 切换协议：重置上下文，重置接口 必须立即被执行，不能压入任务队列中，否则切换后就绪的读事件处理方式还是原来的处理方式
    // 防备新的事件触发后，切换任务还没被执行，数据使用原来协议进行处理
    void Upgrade(const Any& context, const ConnectedCallBack& conn,
                 const MessageCallBack& msg, const ClosedCallBack& closed, 
                 const AnyEventCallBack& event)
    {
        _loop->AssertInLoop();
        _loop->RunInLoop(std::bind(&Connection::Upgrade, this, context, conn, msg, closed, event));
    }
};

class Acceptor
{
private:
    Socket _socket;
    EventLoop* _loop;
    Channel _channel;
    using AcceptCallBack = std::function<void(int)>;
    AcceptCallBack _accept_callback; 
private:
    // 对套接字的读事件就绪处理回调函数，调用_accept_callback进行处理
    void HandlerRead()
    {
        int newfd = _socket.Accept();
        if (newfd < 0)
            return;
        if (_accept_callback) 
            _accept_callback(newfd); 
    }
    int CreateServer(uint16_t port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }
public:
    // 不能在构造函数中启动读事件监控，否则立马就绪的话由于回调函数还没设置，导致新连接数据无法处理且资源泄露
    Acceptor(EventLoop* loop, uint16_t port)
    :_socket(CreateServer(port)), _loop(loop), _channel(loop, _socket.Fd())
    {
        _channel.SetReadCallBack(std::bind(&Acceptor::HandlerRead, this));
    }
    void SetAcceptCallBack(const AcceptCallBack& cb) { _accept_callback = cb; }
    void Listen() { _channel.EnableRead(); }
};

class LoopThread
{
private:
    // 当线程创建出来但是EventLoop还没有创建出来的时候，这时候获取loop对象应该到对应的条件变量下等待
    std::mutex _mutex;  
    std::condition_variable _cond;  
    EventLoop* _loop;              // 线程对应的EventLoop对象
    std::thread _thread;            // EventLoop线程
private:
    void ThreadEntry()
    {
        EventLoop loop;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _loop = &loop;
            _cond.notify_all();
        }
        _loop->Start();
    }
public:
    LoopThread()
    :_thread(std::bind(&LoopThread::ThreadEntry, this)), _loop(nullptr)
    {}
    EventLoop* GetLoop()
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(lock, [&](){ return _loop != nullptr; });
        }
        return _loop;
    }
};

class LoopThreadPool
{
private:
    int _thread_count;                  // 从属Reactor线程的数量
    int _next_idx;                      // RR轮转下一个线程
    EventLoop* _baseloop;               // 主Reactor,如果从属Reactor数量为0，那么所有监控都在主线程中
    std::vector<LoopThread*> _threads;  // 保存创建的LoopThread
    std::vector<EventLoop*> _loops;     // 保存从属EventLoop
public:
    LoopThreadPool(EventLoop* baseloop)
    :_thread_count(0), _next_idx(0), _baseloop(baseloop)
    {}
    void SetThreadCount(int count) { _thread_count = count; }
    void Create()
    {
        _threads.resize(_thread_count);
        _loops.resize(_thread_count);
        for (int i = 0; i < _thread_count; i++)
        {
            _threads[i] = new LoopThread;
            _loops[i] = _threads[i]->GetLoop();
        }
    }
    EventLoop* NextLoop()
    {
        if (_thread_count == 0) 
            return _baseloop;
        _next_idx = (_next_idx + 1) % _thread_count;
        return _loops[_next_idx]; 
    } 
};

class TcpServer
{
private:
    uint64_t _next_id;                                      // 递增的连接/任务id
    uint16_t _port;                                         // 服务监听的端口
    int _timeout;                                           // 连接非活跃销毁超时事件
    bool _enable_inactive_release;                          // 是否启用连接非活跃销毁
    EventLoop _baseloop;                                    // 主Reactor
    Acceptor _acceptor;                                     // 监听套接字
    LoopThreadPool _pool;                                   // 从属Reactor线程池
    std::unordered_map<uint64_t, PtrConnection> _conns;     // 对所有通信连接的管理

    // 用户设置的一系列回调函数
    using ConnectedCallBack = std::function<void(const PtrConnection&)>;
    using MessageCallBack = std::function<void(const PtrConnection&, Buffer*)>; 
    using ClosedCallBack = std::function<void(const PtrConnection&)>; 
    using AnyEventCallBack = std::function<void(const PtrConnection&)>; 
    using Functor = std::function<void()>;
    // 这四个函数是给服务器来设置的，而服务器是给用户设置的
    ConnectedCallBack _connected_callback; 
    MessageCallBack _message_callback; 
    ClosedCallBack _closed_callback; 
    AnyEventCallBack _event_callback; 
private:
    void RunAfterInLoop(const Functor& cb, int delay)
    {
        _next_id++;
        _baseloop.TimerAdd(_next_id, delay, cb);
    }
    // 创建新连接进行管理
    void NewConnection(int fd)
    {
        _next_id++;
        PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
        conn->SetConnectedCallBack(_connected_callback);
        conn->SetClosedCallBack(_closed_callback);
        conn->SetMessageCallBack(_message_callback);
        conn->SetAnyEventCallBack(_event_callback);
        conn->SetSvrClosedCallBack(std::bind(&TcpServer::RemoveConnection, this, std::placeholders::_1));
        if (_enable_inactive_release)
            conn->EnableInactiveRelease(_timeout);
        conn->Established();
        _conns.insert(std::make_pair(_next_id, conn));
    }
    // 从_conns中移除连接
    void RemoveConnectionInLoop(const PtrConnection& conn)
    {
        auto it = _conns.find(conn->Id());
        if (it != _conns.end())
        {
            _conns.erase(it);
        }
        // DBG_LOG("_conns: %ld", _conns.size());
    }
    void RemoveConnection(const PtrConnection& conn)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn));
    }
public:
    TcpServer(uint16_t port)
    :_next_id(0), _port(port), _enable_inactive_release(false), _acceptor(&_baseloop, _port), _pool(&_baseloop)
    {
        _acceptor.SetAcceptCallBack(std::bind(&TcpServer::NewConnection, this, std::placeholders::_1));
        _acceptor.Listen();
    }
    void SetThreadCount(int count) { _pool.SetThreadCount(count); }
    void SetConnectedCallBack(const ConnectedCallBack& cb) { _connected_callback = cb; }
    void SetMessageCallBack(const MessageCallBack& cb) { _message_callback = cb; }
    void SetClosedCallBack(const ClosedCallBack& cb) { _closed_callback = cb; }
    void SetAnyEventCallBack(const AnyEventCallBack& cb) { _event_callback = cb; }
    void EnableInactiveRelease(int timeout) { _enable_inactive_release = true; _timeout = timeout; }
    // 添加定时任务
    void RunAfter(const Functor& cb, int delay) { _baseloop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, cb, delay)); }
    void Start() { _pool.Create(); _baseloop.Start(); }

};


class NetWork
{
public:
    NetWork()
    {
        DBG_LOG("SIGPIPE INIT");
        signal(SIGPIPE, SIG_IGN);
    } 
};
static NetWork nw;